package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户登录
     *
     * @param map
     * @return
     */
    public Map login(Map map) {
        //1.获取map中的数据
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //2.判断验证码是否一致
        String key = Constants.CAP_CODE + uuid;
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        //删除redis中的key
        redisTemplate.delete(key);
        //3.根据用户名查询管理员对象
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        //4.判断用户是否存在和密码是否正确
        password = SecureUtil.md5(password);
        if (StringUtils.isEmpty(admin) || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或密码错误");
        }
        //5.生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", admin.getId());
        tokenMap.put("username", admin.getUsername());
        String token = JwtUtils.getToken(tokenMap);
        //6、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;
    }

    /**
     * 用户详细信息
     * @return
     */
    public AdminVo profile() {
        //1.获取id
        Long userId = AdminHolder.getUserId();
        //2.调用mapper查询信息
        Admin admin = adminMapper.selectById(userId);
        //3.构造vo返回
        return AdminVo.init(admin);
    }
}
